package Concurrency2.Chapter04_Visibility_Orderliness;

import java.util.concurrent.*;

/**
 * Instruction：Reordering
 * Author：@author MaLi
 */
public class T03_Orderliness {
    private static int x = 0, y = 0;
    private static int a = 0, b = 0;
    private static CountDownLatch latch = null;

    public static void main(String[] args) throws InterruptedException {
        ExecutorService service = Executors.newFixedThreadPool(2);
        for (;;) {
            latch = new CountDownLatch(2);
            service.submit(() -> {
                a = 1;
                x = b;
                latch.countDown();
            });

            service.submit(() -> {
                b = 1;
                y = a;
                latch.countDown();
            });
            latch.await();
            if (x == 0 && y == 0) {
                System.err.println("x: " + x + " ,y: " + y);
            }
        }

        /*for (; ; ) {
            Thread t1 = new Thread(() -> {
                a = 1;
                x = b;
            });

            Thread t2 = new Thread(() -> {
                b = 1;
                y = a;
            });
            t1.start();
            t2.start();
            t1.join();
            t2.join();
            if (x == 0 && y == 0) {
                System.err.println("x: " + x + " ,y: " + y);
            }
        }*/
    }
}
